package cn.nawang.ebeim.api.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import cn.nawang.ebeim.api.comm.PageList;
import cn.nawang.ebeim.api.comm.Pages;
import cn.nawang.ebeim.api.comm.SearchFormParams;
import cn.nawang.ebeim.api.domain.Customer;
import cn.nawang.ebeim.api.domain.TbStorageStrategy;
import cn.nawang.ebeim.api.service.CustomerService;
import cn.nawang.ebeim.api.service.TbStorageStrategyService;
import cn.nawang.ebeim.api.utils.Constant;
import cn.nawang.ebeim.api.utils.ValidateUtil;

/**
 * @ClassName: TbStorageStrategyController
 * @Description: TODO
 * @author fanyb
 * @date Oct 12, 2015 11:42:23 AM
 * @version v1.0
 */
@RestController
public class TbStorageStrategyController {
  private static final Logger LOG = LoggerFactory.getLogger(TbStorageStrategyController.class);

  @Autowired
  private TbStorageStrategyService tbStorageStrategyService;
  
  @Autowired
  private CustomerService customerService;

  /**
   * 
   * @author lizh
   * @Description: TODO
   * @param customerId
   * @return Map<String,Object>
   * @date Oct 12, 201511:49:52 AM
   *
   * @修改人
   * @修改日期
   */
  @RequestMapping(value = "/token/storage_strategyService/findCloudId/customer_id", method = RequestMethod.GET)
  public Map<String, Object> findCloudIdByCustomerId(String customerId) {
    LOG.debug("findCloudIdByCustomerId {}", customerId);
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("code", Constant.CODE_ERROR);
    map.put("list", tbStorageStrategyService.findByCustomerId(customerId));
    map.put("code", Constant.CODE_SUCCESS);
    LOG.debug("findCloudIdByCustomerId {}", map);
    return map;
  }

  /**
   * 
   * @author fanyb
   * @Description: 根据storageCloudId判断tbStorageStrategy对象是否存在
   * @param storageCloudId
   * @return Map<String,Object>
   * @date Oct 12, 20151:56:42 PM
   *
   * @修改人
   * @修改日期
   */
  @RequestMapping(value = "/token/tb_storage_strategy/storage_cloud_id", method = RequestMethod.GET)
  public Map<String, Object> findByStorageCloudId(String storageCloudId) {
    LOG.debug("findByStorageCloudId {}", storageCloudId);
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("code", Constant.CODE_ERROR);
    boolean isExist = tbStorageStrategyService.findByfindByStorageCloudId(storageCloudId);
    map.put("code", Constant.CODE_SUCCESS);
    map.put("message", isExist);
    LOG.debug("findByStorageCloudId {}", map);
    return map;
  }

  /**
   * 
   * @author fanyb
   * @Description: 新增tbStorageStrategy
   * @param tbStorageStrategy
   * @return Map<String,Object>
   * @date Oct 19, 20154:40:16 PM
   *
   * @修改人
   * @修改日期
   */
  @RequestMapping(value = "/tb_storage_strategy/add", method = RequestMethod.POST)
  public Map<String, Object> add(TbStorageStrategy tbStorageStrategy) {
    LOG.debug("/tb_storage_strategy/add {}", tbStorageStrategy);
    Map<String, Object> map = new HashMap<String, Object>();
    boolean valid=valid(map,tbStorageStrategy);
    if(!valid){
      return map;
    }
    boolean isSuccess = tbStorageStrategyService.add(tbStorageStrategy);
    if (isSuccess) {
      map.put("code", Constant.CODE_SUCCESS);
      map.put("desc", "新增成功。");
    } else {
      map.put("code", Constant.CODE_ERROR);
      map.put("desc", "服务器忙，请稍后再试。");
    }
    LOG.debug("add {}", map);
    return map;
  }

  /**
   * 
   * @author fanyb
   * @Description: 分页列表
   * @param page
   * @param request
   * @return Object
   * @date Oct 19, 20158:23:17 PM
   *
   * @修改人
   * @修改日期
   */
  @RequestMapping(value = "/tb_storage_strategy/page_list", method = RequestMethod.GET)
  public Object findAllByPaging(Pages page, HttpServletRequest request) {
    LOG.debug("/tb_storage_strategy/page_list {}", page);
    Map<String, Object> map = new HashMap<String, Object>();
    // 组装查询条件
    List<SearchFormParams> dtovect = new ArrayList<SearchFormParams>();
    // 推送消息
    String customerId = request.getParameter("customerId");
    if (!StringUtils.isEmpty(customerId)) {
      dtovect.add(new SearchFormParams("tss.customerId", customerId, "customerId",
          SearchFormParams.STRING_TYPE));
    }
    String name = request.getParameter("name");
    if (!StringUtils.isEmpty(name)) {
      dtovect.add(new SearchFormParams("sc.name", name, "name",
          SearchFormParams.STRING_TYPE));
    }
    if (dtovect.size() > 0) {
      page.setSearchFormParams(dtovect.toArray(new SearchFormParams[dtovect.size() - 1]));
    }
    PageList pagelist = tbStorageStrategyService.findPageList(page);
    map.put(Constant.JSON_CODE, Constant.CODE_200);
    map.put("list", pagelist.getObjList());
    map.put("page", pagelist.getPage());
    LOG.debug("findAllByPaging {}", map);
    return map;
  }

  /**
   * 
   * @author fanyb
   * @Description: 根据id获取实体
   * @param id
   * @return Object
   * @date Oct 19, 20158:23:34 PM
   *
   * @修改人
   * @修改日期
   */
  @RequestMapping(value = "/tb_storage_strategy/id", method = RequestMethod.GET)
  public Object findOne(String id) {
    LOG.debug("/tb_storage_strategy/id {}", id);
    Map<String, Object> map = new HashMap<String, Object>();
    TbStorageStrategy tbStorageStrategy = tbStorageStrategyService.findOne(id);
    if (tbStorageStrategy == null) {
      map.put("code", Constant.CODE_ERROR);
    } else {
      map.put("code", Constant.CODE_SUCCESS);
      map.put("obj", tbStorageStrategy);
    }
    LOG.debug("findAllByPaging {}", map);
    return map;
  }

  /**
   * 
   * @author fanyb
   * @Description: 批量删除
   * @param ids
   * @return Object
   * @date Oct 19, 20158:23:50 PM
   *
   * @修改人
   * @修改日期
   */
  @RequestMapping(value = "/tb_storage_strategy/delete", method = RequestMethod.GET)
  public Object delete(String[] ids) {
    LOG.debug("/tb_storage_strategy/delete ids" + ids);
    Map<String, Object> map = new HashMap<String, Object>();
    boolean isSuccess = tbStorageStrategyService.delete(ids);
    if (isSuccess) {
      map.put("code", Constant.CODE_SUCCESS);
      map.put("desc", "更新成功。");
    } else {
      map.put("code", Constant.CODE_ERROR);
      map.put("desc", "服务器忙，请稍后再试。");
    }
    LOG.debug("delete {}", map);
    return map;
  }

  /**
   * 
   * @author fanyb
   * @Description: 更新
   * @param tbStorageStrategy
   * @return Object
   * @date Oct 19, 20158:24:02 PM
   *
   * @修改人
   * @修改日期
   */
  @RequestMapping(value = "/tb_storage_strategy/update", method = RequestMethod.GET)
  public Object update(TbStorageStrategy tbStorageStrategy) {
    LOG.debug("/tb_storage_strategy/update {}", tbStorageStrategy);
    Map<String, Object> map = new HashMap<String, Object>();
    boolean valid=valid(map,tbStorageStrategy);
    if(!valid){
      return map;
    }
    boolean isSuccess = tbStorageStrategyService.update(tbStorageStrategy);
    if (isSuccess) {
      map.put("code", Constant.CODE_SUCCESS);
      map.put("desc", "更新成功。");
    } else {
      map.put("code", Constant.CODE_ERROR);
      map.put("desc", "服务器忙，请稍后再试。");
    }
    LOG.debug("update {}", map);
    return map;
  }

  
  public boolean valid(Map<String, Object> resultMap, TbStorageStrategy tbStorageStrategy) {
    Customer customer=customerService.findOne(tbStorageStrategy.getCustomerId());
    List list=tbStorageStrategyService.findByCustomerId(tbStorageStrategy.getCustomerId());
    int count=0;
    if(list!=null&&!list.isEmpty()){
      count=list.size();
    }
    if(ValidateUtil.isEmpty(tbStorageStrategy.getId())&&customer.getMaxCopys()<=count){
      resultMap.put("desc", "很抱歉，当前客户最大备份次数已经达到最大值。");
      return false;
    }
    // 主存储是否唯一判断对象
    TbStorageStrategy isPrimarytss=tbStorageStrategyService.findByIsPrimary(tbStorageStrategy.getCustomerId(), 0);
    // 云存储策略是否唯一判断
    TbStorageStrategy byCusIdAndscloudId=tbStorageStrategyService.findByStorageCloudIdAndCustomerId(
      tbStorageStrategy.getCustomerId(), tbStorageStrategy.getStorageCloudId());
    if (tbStorageStrategy.getIsPrimary()==0
        &&!ValidateUtil.isNull(isPrimarytss)
        &&!isPrimarytss.getId().equals(tbStorageStrategy.getId())) {
      resultMap.put("desc", "很抱歉，当前客户已经有一个主存储，请将选项设置为否。");
      return false;
    }
    
    if (!ValidateUtil.isNull(byCusIdAndscloudId)
        &&!byCusIdAndscloudId.getId().equals(tbStorageStrategy.getId())) {
      resultMap.put("desc", "很抱歉，当前云存储策略已存在，请勿重复分配。");
      return false;
    }
    return true;
  }
}
